#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <gmp.h>

#define NTH 8

mpf_t total_p_g[NTH];
mpf_t in_p_g[NTH];

void *pontos(void *nthread);

void main (void)
{
    int i;
    srand48(time(NULL));
    mpf_set_default_prec(33219281);
    pthread_t threads[NTH];

    mpf_t total_p_l,in_p_l,pie;

    mpf_init(total_p_l);
    mpf_set_ui(total_p_l,0);

    mpf_init(in_p_l);
    mpf_set_ui(in_p_l,0);

    mpf_init(pie);
    mpf_set_ui(pie,0);

    for(i = 0; i < NTH; i++){
        pthread_create (&threads[i] , NULL , pontos , &i);
    }

    for(i = 0; i < NTH; i++){
        pthread_join(threads[i] , NULL);
    }

    for(i = 0; i < NTH; i++){
        mpf_add_ui(total_p_l,total_p_g[i],1);
        mpf_add_ui(in_p_l,in_p_g[i],1);
    }

    mpf_mul_ui(in_p_l,in_p_l,4);
    mpf_div(pie,in_p_l,total_p_l);

    mpf_clear (total_p_l);
    mpf_clear (in_p_l);

    for(i = 0; i < NTH; i++){
        mpf_clear (total_p_g[i]);
        mpf_clear (in_p_g[i]);
    }



    gmp_printf("Pi %.10000Ff \n",pie);
    mpf_clear (pie);
}

void *pontos(void *nthread)
{

    long double x,y;
    int idthread,i;

    idthread = *((int *)nthread);


    mpf_init(total_p_g[idthread]);
    mpf_init(in_p_g[idthread]);
    mpf_set_ui(total_p_g[idthread],0);
    mpf_set_ui(in_p_g[idthread],0);

    for(i = 0; i < 1000000;i++){

        x = (long double)rand()/RAND_MAX;
        y = (long double)rand()/RAND_MAX;

        if(((x*x) + (y*y)) <= 1.0)
        {
            mpf_add_ui(in_p_g[idthread],in_p_g[idthread],1);
        }
        mpf_add_ui(total_p_g[idthread],total_p_g[idthread],1);
    }
    pthread_exit(0);

}
